Delegate (swfit)
委譲の話
「Delegate」という機能があるわけではなく、そういうデザインパターン
gpt-5.icon
あるオブジェクトの処理の一部を別のオブジェクトに任せる設計パターンです。
Swiftでは主に Protocol (swift)を使って実装します。
目的は次の2つです。
処理の役割を分離する
イベントを外部へ通知する
1. Delegateの基本イメージ
例:ボタンが押されたとき
Button → 「押された」というイベントを発生
ViewController → 押された時の処理を書く
Button自身は「何をするか」を知らず、Delegateに任せます
2. Swiftでの基本実装
① protocolを作る
code:swift
protocol ButtonDelegate {
func didTapButton()
}
これは「ボタンが押された時に呼ばれる関数」を定義しています。
② Delegateを持つクラス
code:swift
class Button {
var delegate: ButtonDelegate?
func tap() {
delegate?.didTapButton()
}
}
ボタンが押されたとき
code:_
delegate?.didTapButton()
で delegateに処理を任せます。
③ Delegateを実装する側
code:swift
class ViewController: ButtonDelegate {
func didTapButton() {
print("Button tapped")
}
}
④ delegateを設定
code:swift
let button = Button()
let vc = ViewController()
button.delegate = vc
button.tap()
実行結果
code:_
Button tapped
まあ、わかるけど、なんでよく使うん?という感じはあるmrsekut.icon
Swiftだから目新しいとかいう話ではなかった
4. iOSでDelegateが使われる例
Delegateは UIKitで非常によく使われます。
UITableView
code:swift
UITableViewDelegate
UITableViewDataSource
例
code:swift
func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath)
セルがタップされたことを通知。
UITextField
code:swift
UITextFieldDelegate
例
code:_
textFieldDidBeginEditing
URLSession
code:swift
URLSessionDelegate
通信イベントを通知。